using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using NetWing.Common.Data.Filter;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Drawing;
using NetWing.Common.Pinyin;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;
using System.Data.Linq;
using NetWing.Common.EF;
using static NetWing.BPM.Admin.JydModleOrder.ashx.ajax_submit;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;

namespace NetWing.BPM.Admin.JydOrder.ashx
{
    /// <summary>
    /// 接件单 的摘要说明
    /// </summary>
    public class JydOrderHandler : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// datetime转换Unix时间
        /// </summary>
        public static long timeunix(System.DateTime time)
        {
            System.DateTime dateTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - dateTime.Ticks) / 10000;
            return t;
        }
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int k;
            int pageStatus = 0;//页面当前状态
            int orderStatus = 0;//订单当前状态
            var json = HttpContext.Current.Request["json"];
            var detailJson = HttpContext.Current.Request["d"];//接收参数d代表详细子表数据
            //主表json
            var rpm = new RequestParamModel<JydOrderModel>(context) { CurrentContext = context };
            //子表json
            var rpmA = new RequestParamModel<JydOrderDetailModel>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                //主表json
                rpm = JSONhelper.ConvertToObject<RequestParamModel<JydOrderModel>>(json);
                rpm.CurrentContext = context;
                //子表json
                rpmA = JSONhelper.ConvertToObject<RequestParamModel<JydOrderDetailModel>>(json);
                rpmA.CurrentContext = context;
            }
            else //不以json方式提交 没有带参数?json=的时候 必须带 ?action=
            {
                rpm.Action = context.Request["action"];
            }

            switch (rpm.Action)
            {
                case "qrcode"://二维码
                    #region 二维码
                    //传入两个参数action=qrcode&mainkeyid=
                    string b64 = QRCode.GenerateBase64(@"JydModleOrder\img\jyd.png", ConfigHelper.GetValue("website") + "JydModleOrder/taskQRcode.aspx?KeyID=" + context.Request["mainkeyid"]);
                    context.Response.Write(b64);
                    #endregion
                    break;
                case "jieqing":
                    //在写处理文件的时候我犯了一个极大的错误,好在被老板及时发现,多种提交你只能写一个处理程序,这样才是一个合格的代码
                    #region  结清订单

                    string Orderi = context.Request["OrderID"];
                    string statu = context.Request["status"];
                    //增加订单状态,status在加3的时候可能会报转换int错误

                    string msql = "UPDATE jydOrder SET mystatus=3,status= status + ',3',updatetime='"+DateTime.Now.ToString("yyyy-MM-dd")+"' where OrderID='" + Orderi + "'";
                    int status = SqlEasy.ExecuteNonQuery(msql);
                    //返回结果

                    if (status > 0)
                    {
                        //写日志
                        LogModel logxh = new LogModel();
                        logxh.BusinessName = SysVisitor.Instance.cookiesUserId + "结清成功";
                        logxh.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                        logxh.OperationTime = DateTime.Now;
                        logxh.PrimaryKey = "";
                        logxh.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        logxh.SqlText = msql;
                        logxh.TableName = "jydOrder";
                        logxh.note = msql;
                        logxh.OperationType = (int)OperationType.Update;
                        LogDal.Instance.Insert(logxh);


                        context.Response.Write("{\"status\":1,\"msg\":\"订单已结清！\"}");
                    }
                    else
                    {
                        context.Response.Write("{\"status\":0,\"msg\":\"结清订单失败！\"}");
                    }
                    #endregion
                    break;

                case "zuofei"://作废订单
                    #region 作废订单

                    string OrderId = context.Request["OrderID"];
                    string mystatus = context.Request["mystatus"];
                    //增加订单状态
                    if (mystatus == "3")
                    {
                        context.Response.Write("{\"code\":13,\"msg\":\"已完成的订单,不能作废！\"}");
                    }
                    else
                    {

                        string code = "update jydOrder set mystatus = 4,status=status + ',4',jexx = 0 where OrderId = '" + OrderId + "'";//追加更新status 为,4
                        int codeq = SqlEasy.ExecuteNonQuery(code);
                        //返回结果
                        if (codeq > 0)
                        {
                            LogModel logxx = new LogModel();
                            logxx.BusinessName = SysVisitor.Instance.cookiesUserId + "作废成功";
                            logxx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                            logxx.OperationTime = DateTime.Now;
                            logxx.PrimaryKey = "";
                            logxx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                            logxx.SqlText = code;
                            logxx.TableName = "jydOrder";
                            logxx.note = code;
                            logxx.OperationType = (int)OperationType.Update;
                            LogDal.Instance.Insert(logxx);

                            context.Response.Write("{\"code\":1,\"msg\":\"订单已作废！\"}");
                        }
                        else
                        {
                            context.Response.Write("{\"code\":0,\"msg\":\"订单作废失败！\"}");
                        }
                    }
                    #endregion
                    break;

                case "cuidxgf":
                    #region 修改催单状态
                    try
                    {
                        string KeyId = context.Request["KeyId"];
                        //增加订单状态
                        string codeqq = "update jydOrder set FlowStatus = 0 where KeyId = '" + KeyId + "'";//追加更新status 为,4
                        int codeii = SqlEasy.ExecuteNonQuery(codeqq);                                                                                                      //返回结果
                        if (codeii > 0)
                        {
                            //写日志
                            LogModel loogx = new LogModel();
                            loogx.BusinessName = SysVisitor.Instance.cookiesUserId + "修改催单成功";
                            loogx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                            loogx.OperationTime = DateTime.Now;
                            loogx.PrimaryKey = "";
                            loogx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                            loogx.SqlText = codeqq;
                            loogx.TableName = "jydOrder";
                            loogx.note = codeqq;
                            loogx.OperationType = (int)OperationType.Update;
                            LogDal.Instance.Insert(loogx);

                            context.Response.Write("{\"code\":0,\"msg\":\"催单状态修改成功！\"}");
                        }
                        else
                        {
                            context.Response.Write("{\"code\":1000,\"msg\":\"催单状态修改失败！\"}");
                        }
                    }
                    catch (Exception e)
                    {
                        WriteLogs.WriteLogsE("Logs", "DINGDError >> caozuo", e.Message + " >>> " + e.StackTrace);
                    }
                    #endregion
                    break;


                case "shenhe"://2019-03-20新增功能，管理员审核采购单
                    #region  2019-03-20新增功能，管理员审核采购单
                    try
                    {
                        string KeyId = context.Request["KeyId"];

                        string shnhe = "update Psi_BuyDetails set examine_status=3 where Keyid = " + KeyId + "";
                        int codeii = SqlEasy.ExecuteNonQuery(shnhe);
                        if (codeii > 0)
                        {
                            //写日志
                            LogModel loogx = new LogModel();
                            loogx.BusinessName = SysVisitor.Instance.cookiesUserId + "修改催单成功";
                            loogx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                            loogx.OperationTime = DateTime.Now;
                            loogx.PrimaryKey = "";
                            loogx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                            loogx.SqlText = shnhe;
                            loogx.TableName = "Psi_BuyDetails";
                            loogx.note = shnhe;
                            loogx.OperationType = (int)OperationType.Update;
                            LogDal.Instance.Insert(loogx);

                            context.Response.Write("{\"code\":0,\"msg\":\"审核状态修改成功！\"}");
                        }
                        else
                        {
                            context.Response.Write("{\"code\":1000,\"msg\":\"审核状态修改失败！\"}");
                        }


                    }
                    catch (Exception e)
                    {
                        WriteLogs.WriteLogsE("Logs", "DINGDError >> caozuo", e.Message + " >>> " + e.StackTrace);
                    }
                    #endregion
                    break;
                case "yiruku"://2019-03-20新增功能，收货入库
                    #region 2019-03-20新增功能，收货入库
                    try
                    {
                        ////keyid,库存ID,规格,分类,编号,名称,单位,数量,价格,金额,经手人
                        //var btnnn = '<a onclick="caigoudan(\'' + rhfhfgow.KeyId + '\',\'' + rhfhfgow.goodsId + '\',\'' + rhfhfgow.specs + '\',\'' + rhfhfgow.goodsClassName + '\',\'' + rhfhfgow.edNumber + '\',
                        //\'' + rhfhfgow.goodsName + '\',\'' + rhfhfgow.unit + '\',\'' + rhfhfgow.buyNum + '\',\'' + rhfhfgow.buyPrice + '\',\'' + rhfhfgow.buyAllMoney + '\',\'' + rhfhfgow.Contacts + '\')"
                        string KeyId = context.Request["KeyId"];//keyid
                        string goooid = context.Request["gooid"];//库存ID
                        string specs = context.Request["specs"];//规格
                        string goodsClassName = context.Request["goodsClassName"];//,分类,
                        string edNumber = context.Request["edNumber"];//编号,
                        string goodsName = context.Request["goodsName"];//名称,
                        string unit = context.Request["unit"];//单位,
                        string buyNum = context.Request["buyNum"];//数量,
                        string buyPrice = context.Request["buyPrice"];//价格,
                        string str = buyPrice.Substring(1);
                        string buyAllMoney = context.Request["buyAllMoney"];//金额,
                        string Contacts = context.Request["Contacts"];//经手人
                        #region
                        DataTable shenhe = SqlEasy.ExecuteDataTable("select * from Psi_BuyDetails where Keyid = " + KeyId + "");
                        Psi_GoodsModel model = new Psi_GoodsModel();
                        int stock = int.Parse(shenhe.Rows[0]["buyNum"].ToString());
                        double buyprice = System.Convert.ToDouble(shenhe.Rows[0]["buyPrice"].ToString());
                        string stocksql = "update Psi_Goods set stock=stock+" + stock + ",buyprice=" + (-buyprice) + ",up_time='" + DateTime.Now.ToString() + "' where keyid=" + goooid + "";
                        int stocko = SqlEasy.ExecuteNonQuery(stocksql);
                        if (stocko > 0)
                        {
                            DataRow adataRow = SqlEasy.ExecuteDataRow("select * from Psi_Goods where keyid='" + goooid + "'");
                            string shnhe = "update Psi_BuyDetails set examine_status = 5 where Keyid = " + KeyId + "";
                            int Warehousing = SqlEasy.ExecuteNonQuery(shnhe);
                            //写日志
                            if (Warehousing > 0)
                            {

                                SqlTransaction atran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                                Psi_goodssuanModel psi_Goodssuan = new Psi_goodssuanModel
                                {
                                    goodsID = int.Parse(goooid),
                                    spercs = specs,
                                    goodsclassname = goodsClassName,
                                    goodsNo = adataRow["goodsNo"].ToString(),
                                    goodsName = goodsName,
                                    unit = unit,
                                    stock = int.Parse(buyNum),
                                    buyprice = decimal.Parse(str),
                                    add_time = DateTime.Now,
                                    up_time = DateTime.Now,
                                    status = "0",//0是入库单
                                    number = int.Parse(buyNum)//当前实际数量
                                };
                                DbUtils.tranInsert(psi_Goodssuan, atran);//提交流程操作记录
                                atran.Commit();//提交事务
                                LogModel loogx = new LogModel();
                                loogx.BusinessName = SysVisitor.Instance.cookiesUserId + "修改入库成功";
                                loogx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                                loogx.OperationTime = DateTime.Now;
                                loogx.PrimaryKey = "";
                                loogx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                                loogx.SqlText = shnhe;
                                loogx.TableName = "Psi_BuyDetails";
                                loogx.note = shnhe;
                                loogx.OperationType = (int)OperationType.Update;
                                LogDal.Instance.Insert(loogx);
                                #endregion
                                context.Response.Write("{\"code\":0,\"msg\":\"商品成功入库！\"}");
                            }
                            else
                            {
                                context.Response.Write("{\"code\":1000,\"msg\":\"商品入库失败！\"}");
                            }
                        }


                    }
                    catch (Exception e)
                    {
                        WriteLogs.WriteLogsE("Logs", "DINGDError >> caozuo", e.Message + " >>> " + e.StackTrace);
                    }
                    #endregion
                    break;
                case "caigoudan"://2019-03-20新增功能，生成
                    #region 生成采购单
                    string keyid = context.Request["KeyId"];
                    string gooid = context.Request["gooid"];
                    string cai = "update Psi_BuyDetails set examine_status=3 where Keyid = " + keyid + "";
                    int caio = SqlEasy.ExecuteNonQuery(cai);
                    if (caio > 0)
                    {
                        //写日志
                        LogModel loogx = new LogModel();
                        loogx.BusinessName = SysVisitor.Instance.cookiesUserId + "生成采购单成功";
                        loogx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                        loogx.OperationTime = DateTime.Now;
                        loogx.PrimaryKey = "";
                        loogx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        loogx.SqlText = cai;
                        loogx.TableName = "Psi_BuyDetails";
                        loogx.note = cai;
                        loogx.OperationType = (int)OperationType.Update;
                        LogDal.Instance.Insert(loogx);

                        context.Response.Write("{\"code\":0,\"msg\":\"生成采购单成功！\"}");
                    }
                    else
                    {
                        context.Response.Write("{\"code\":1000,\"msg\":\"生成采购单失败！\"}");
                    }
                    #endregion
                    break;
                case "caigoudaohuo"://2019-03-20新增功能，生成
                    #region 2019-03-20新增功能，生成采购单到货
                    string keeyid = context.Request["KeyId"];
                    string gooide = context.Request["gooid"];
                    string caioi = "update Psi_BuyDetails set examine_status=4 where Keyid = " + keeyid + "";
                    int caioo = SqlEasy.ExecuteNonQuery(caioi);
                    if (caioo > 0)
                    {
                        //写日志
                        LogModel loogx = new LogModel();
                        loogx.BusinessName = SysVisitor.Instance.cookiesUserId + "采购单到货";
                        loogx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                        loogx.OperationTime = DateTime.Now;
                        loogx.PrimaryKey = "";
                        loogx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        loogx.SqlText = caioi;
                        loogx.TableName = "Psi_BuyDetails";
                        loogx.note = caioi;
                        loogx.OperationType = (int)OperationType.Update;
                        LogDal.Instance.Insert(loogx);

                        context.Response.Write("{\"code\":0,\"msg\":\"采购到货成功！\"}");
                    }
                    else
                    {
                        context.Response.Write("{\"code\":1000,\"msg\":\"采购到货失败！\"}");
                    }
                    #endregion
                    break;
                case "jjy"://返回接件员及接件员ID
                    #region 返回接件员及接件员ID
                    context.Response.Write("{\"jjy\":\"" + SysVisitor.Instance.cookiesUserName + "\",\"dt\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\"}");
                    #endregion
                    break;

                case "zrrid"://返回接件员及接件员ID
                    #region 返回接件员及接件员ID
                    context.Response.Write("{\"zrrid\":\"" + SysVisitor.Instance.cookiesUserId + "\",\"zrr\":\"" + SysVisitor.Instance.cookiesUserName + "\"}");
                    #endregion
                    break;
                case "add"://开单  2018-10-23 修改 开单时开出工作流
                    #region 数据库事务
                    SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {
                        #region 先插入主表
                        int mainInsertedId = 0;//（主表公用）主表插入的ID
                        string edNumber = common.mjcommon.getedNumberJyd();
                        JydOrderModel mainModel = new JydOrderModel();
                        mainModel.InjectFrom(rpm.Entity);
                        mainModel.OrderID = edNumber;
                        //子表赋值给主表
                        mainModel.allyspmc = rpmA.Entity.yspmc;
                        mainModel.status = "0";//添加之后的默认,可在添加时写入
                        mainModel.FlowStatus = "0";
                        string[] arr = edNumber.Split('-');
                        // 子订单个数数组
                        mainModel.OrderInt = int.Parse(arr[3]);
                        mainModel.OrderYear = DateTime.Now.ToString("yyyy-MM-dd");
                        mainModel.jpm = Pinyin.GetCodstring(mainModel.comname).ToLower();//汉字转简拼并小写
                        mainModel.deptid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                        mainModel.adddate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                            mainModel.dept = "总公司";



                        mainInsertedId = DbUtils.tranInsert(mainModel, tran);//往主表插入一条

                        #endregion


                        #region 再插入明细表
                        //JObject jo = JObject.Parse(detailJson);

                        JArray detailArr = JArray.Parse(detailJson);
                        for (int ii = 0; ii < detailArr.Count; ii++)//循环
                        {
                            var detailobj = JSONhelper.ConvertToObject<JydOrderDetailModel>(detailArr[ii]["d"].ToString());//根据模型把明细表转化为obj
                            JydOrderDetailModel detailModel = new JydOrderDetailModel();//初始化明细表模型
                            detailModel.InjectFrom(detailobj);//把obj插入模型
                            detailModel.orderid = mainModel.OrderID;//orderid关联
                            detailModel.omainid = mainInsertedId;
                            int detInsertid = DbUtils.tranInsert(detailModel, tran);////执行写入明细表
                            #region 写工作流 一个子订单一个工作流 订单类型与工作流匹配
                            //1.取得该印刷品类型的流程方案model
                            //SqlDataReader dr = SqlEasy.ExecuteDataReader("select top 1 * from FlowScheme where Schemename='" + detailModel.PrintType + "' ");
                            //FlowSchemeModel fsm = new FlowSchemeModel();
                            //while (dr.Read())
                            //{
                            //    fsm.InjectFrom<ReaderInjection>(dr);
                            //    JObject joflow = new JObject();
                            //    joflow.Add("Code", detailModel.orderid + "_" + mainInsertedId + "_" + detInsertid);//自定义实例编号(这里打算传入订单编号_订单主表keyid_订单子表keyid)
                            //    joflow.Add("CustomName", mainModel.comname + "_" + detailModel.yspmc + "");//自定义流程名称 如卡纸_流程
                            //    joflow.Add("FlowScheme", fsm.SchemeName);//流程方案名称
                            //    joflow.Add("SchemeContent", fsm.SchemeContent);//流程方案内容json格式
                            //    joflow.Add("SchemeId", fsm.KeyId);//流程方案ID
                            //    joflow.Add("Description", SysVisitor.Instance.cookiesUserName + "于" + DateTime.Now.ToString() + "创建");//备注
                            //    NetWing.Model.flow.CreateInstance(joflow);
                            //}
                            //写任务模板,订单印刷类型与任务模板印刷类型相符
                            SqlDataReader dr = SqlEasy.ExecuteDataReader("select top 1 * from jydflowTasktemplate where Printedmattername = '" + detailModel.PrintType + "' and sortid=1");

                            JydflowTasktemplateModel flow = new JydflowTasktemplateModel();
                            while (dr.Read())
                            {
                                flow.InjectFrom<ReaderInjection>(dr);
                                JObject jofow = new JObject();
                                jofow.Add("nodename", dr["nodename"].ToString());//节点名称
                                jofow.Add("operatorID", dr["operatorID"].ToString());//执行人ID
                                jofow.Add("operatorname", dr["operatorname"].ToString());//执行人
                                jofow.Add("orderID", detailModel.orderid);//订单编号
                                jofow.Add("ordername", mainModel.comname + "_" + detailModel.yspmc);//订单名称
                                jofow.Add("sortid", dr["sortid"].ToString());//执行顺序
                                jofow.Add("softdeletion", dr["softdeletion"].ToString());//不执行的
                                jofow.Add("addtime", DateTime.Now.ToString("yyyy-MM-dd"));//创建时间
                                jofow.Add("isitcomplete", 1);//是否完成
                                jofow.Add("PrintedmatterID", dr["PrintedmatterID"].ToString());//订单类型编号
                                jofow.Add("Printedmattername", dr["Printedmattername"].ToString());//订单类型
                                jofow.Add("orderkey", mainInsertedId);//订单
                                jofow.Add("timestamp", dr["timestamp"].ToString());//时间戳
                                jofow.Add("addname", mainModel.comname);//创建人
                                jofow.Add("SchemeContent", detInsertid);//子表id
                                jofow.Add("completeofth", SysVisitor.Instance.cookiesUserName + "于" + DateTime.Now.ToString() + "创建");//完成情况备注








                                NetWing.BPM.Admin.JydflowTasktemplate.templateflow.CreateInstance(jofow);
                            }
                            #endregion
                        }

                        //生成二维码
                        string QRCodeUrl = QRCode.Generate(ConfigHelper.GetValue("website") + "/JydModleOrder/taskQRcode.aspx?KeyID=" + mainInsertedId, @"JydModleOrder\img\jyd.png", DateTime.Now.ToString("yyyyMMdd"));
                        //每添加修改一条数据动态改变二维码
                        DbUtils.tranExecuteNonQuery("update JydOrder set order_img='" + QRCodeUrl + "' where KeyId=" + mainInsertedId, tran);


                        #endregion
                        tran.Commit();//提交事务
                        context.Response.Write(1);

                        //写日志
                        LogModel logxq = new LogModel();
                        logxq.BusinessName = SysVisitor.Instance.cookiesUserId + "开单成功";
                        logxq.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                        logxq.OperationTime = DateTime.Now;
                        logxq.PrimaryKey = "";
                        logxq.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        logxq.SqlText = "开单";
                        logxq.TableName = "jydOrder";
                        logxq.note = "管理员开单成功";
                        logxq.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(logxq);




                    }
                    catch (Exception e)
                    {
                        tran.Rollback();
                        WriteLogs.WriteLogsE("Logs", "Error >> GetQRCode", e.Message + " >>> " + e.StackTrace);

                        //写日志
                        LogModel logxq = new LogModel();
                        logxq.BusinessName = "开单成功失败";
                        logxq.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                        logxq.OperationTime = DateTime.Now;
                        logxq.PrimaryKey = "";
                        logxq.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        logxq.SqlText = "开单";
                        logxq.TableName = "jydOrder";
                        logxq.note = e.Message;
                        logxq.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(logxq);

                        context.Response.Write(-1);
                    }



                    //context.Response.Write(JydOrderBll.Instance.Add(rpm.Entity));
                    #endregion
                    break;
                case "edit"://修改接件单--也就是接件单
                    #region 数据库事务
                    //JydOrderModel d = new JydOrderModel();
                    //d.InjectFrom(rpm.Entity);
                    //d.KeyId = rpm.KeyId;
                    //context.Response.Write(JydOrderBll.Instance.Update(d));
                    pageStatus = 0;//页面接件状态是0

                    SqlTransaction tranedit = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {
                        JydOrderModel d = new JydOrderModel();
                        d.InjectFrom(rpm.Entity);
                        d.KeyId = rpm.KeyId;
                        d.jpm = Pinyin.GetCodstring(d.comname).ToLower();//汉字转简拼并小写
                        //只更新以下主字段
                        //剔除不更新字段"KeyId","OrderYear", "OrderInt", "OrderID", 注意大写的也不更新
                        //"dept", "deptid",这连个字段添加时候就固定以后都不更新
                        string[] up = { "servicetype", "username", "comname", "comnameid", "jpm", "name", "tel", "address", "explain", "deliverydate", "delivery", "adddate", "fk", "yf", "qt", "totalprice", "cfzt", "jjy", "fumoa", "fumob", "yaa", "yab", "tana", "tanb", "zheye", "uva", "uvb", "zd", "db", "bh", "sh", "sk", "huofa", "fahuoren", "ys", "fy", "dha", "dhb", "jexx", "jedx", "yufuk", "yufukuana", "sckd", "sjwcsj", "cpwcsj", "ctpsj", "sbwcsj", "qslsj", "yswcsj", "hjgkssj", "hjgwcsj", "wjgjcsj", "qcpsj", "zdkssj", "dzwcsj", "shryccsj", "shryhcsj", "dbsj", "szp", "sxj", "skje", "zph", "kkyy", "zrr", "rksj", "cksj", "myws", "myysf", "o_myhjg1", "jgzysx", "connman", "kkkje", "allyspmc", "liuchendan", "kaidan", "ywy", "ywyid" };
                        DbUtils.tranUpdateOnlyUpdateFields(d, tranedit, up);
                        #region 更新明细表
                        JArray detailArr = JArray.Parse(detailJson);
                        for (int ii = 0; ii < detailArr.Count; ii++)//循环
                        {
                            var detailobj = JSONhelper.ConvertToObject<JydOrderDetailModel>(detailArr[ii]["d"].ToString());//根据模型把明细表转化为obj
                            JydOrderDetailModel detailModel = new JydOrderDetailModel();//初始化明细表模型
                            detailModel.InjectFrom(detailobj);//把obj插入模型



                            //只更新以下字段 
                            //剔除不更新的字段"KeyId", "orderid", "omainid","kzcc", "zs", "fs", "pss", "pst", "fbyq", "jx",
                            string[] upfiles = { "yspmc", "printtype", "cpcc", "zzf", "zzn", "ym", "sj", "rj", "jp", "zz", "sl", "cc", "dj", "je", "note", "fumoa", "fumob", "yaa", "yab", "tana", "tanb", "zheye", "uva", "uvb", "zd", "db", "bh", "sh", "sk", "sjwcsj", "cpwcsj", "ctpsj", "sbwcsj", "qslsj", "yswcsj", "hjgkssj", "hjgwcsj", "wjgjcsj", "qcpsj", "zdkssj", "dzwcsj", "shryccsj", "shryhcsj", "dbsj", "rksj", "cksj", "zrr", "kkyy", "sxj", "szp", "zph", "myws", "myysf", "O_myhjg", "qianshou", "skje", "wsjgbz", "dddd", "kkkje", "yspmcb", "FileTypeb", "mianb", "munb", "colorb", "pagerb", "O_my_jpb", "O_my_zzb", "ddddb", "zznb", "ymb", "sjb", "rjb", "jpb", "zzb", "fumoab", "fumobb", "yaab", "yabb", "tanab", "tanbb", "zheyeb", "uvab", "uvbb", "zdb", "dbb", "bhb", "shb", "skb", "PrintTypeb", "zzfb", "noteb", "cpccb", "printyes", "kzccb", "zsb", "fsb", "pssb", "pstb", "fbyqb", "jxb", "kkkjeb", "nysl", "ctpa", "ctpb", "zhizhangbb", "songhuo", "xiaoyang", "danwei_m", "danwei_mb", "bz_hx", "bz_wbz_cc", "bz_wbz_gy", "bz_nbz_zz", "bz_nbz_cc", "bz_nbz_gy", "bz_wkz_zz", "bz_wkz_cc", "bz_wkz_gy", "bz_bc_yl", "bz_bc_sl", "bz_bc_mx", "bz_nt", "bz_nt_cc", "bz_nt_mx", "bz_wbz", "zidaihz", "zidaihchz" };
                            DbUtils.tranUpdateOnlyUpdateFields(detailModel, tranedit, upfiles);
                        }
                        //生成二维码
                        string QRCodeUrl = QRCode.Generate(ConfigHelper.GetValue("website") + "/JydModleOrder/QRCodeView.aspx?KeyID=" + d.KeyId, @"JydModleOrder\img\gongch.png", DateTime.Now.ToString("yyyyMMdd"));
                        //每添加修改一条数据动态改变二维码
                        DbUtils.tranExecuteNonQuery("update JydOrder set order_img='" + QRCodeUrl + "' where KeyId=" + d.KeyId, tranedit);

                        #endregion
                        //从数据库里获得订单当前状态
                        orderStatus = (int)DbUtils.tranExecuteScalar("select mystatus from jydorder where keyid=" + d.KeyId + "", tranedit);

                        //为了思路清晰,订单状态单独更新
                        DbUtils.tranExecuteNonQuery("update jydorder set status=status+',0',mystatus=0 where keyid=" + d.KeyId + "", tranedit);

                        //判断是否是超管如果是超管可以任意修改
                        bool isadmin = SysVisitor.Instance.IsAdmin;
                        //if (isadmin)//如果是超管
                        //{
                            tranedit.Commit();//提交事务
                            context.Response.Write("{\"status\":1,\"msg\":\"修改成功\" }");
                            //写日志
                            LogModel llogx = new LogModel();
                            llogx.BusinessName = SysVisitor.Instance.cookiesUserId + "超管修改了接件单";
                            llogx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                            llogx.OperationTime = DateTime.Now;
                            llogx.PrimaryKey = "";
                            llogx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                            llogx.SqlText = "开单";
                            llogx.TableName = "jydOrder";
                            llogx.note = "超管修改了接件单";
                            llogx.OperationType = (int)OperationType.Update;
                            LogDal.Instance.Insert(llogx);
                        //}
                        //else//如果不是超管
                        //{

                        //    //if (orderStatus <= pageStatus)//订单状态小于等于页面状态
                        //    //{


                        //        tranedit.Commit();//提交事务
                        //        context.Response.Write("{\"status\":1,\"msg\":\"修改成功\" }");

                        //        LogModel alogx = new LogModel();
                        //        alogx.BusinessName = SysVisitor.Instance.cookiesUserId + "管理员修改了接件单";
                        //        alogx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                        //        alogx.OperationTime = DateTime.Now;
                        //        alogx.PrimaryKey = "";
                        //        alogx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        //        alogx.SqlText = "开单";
                        //        alogx.TableName = "jydOrder";
                        //        alogx.note = "管理员修改了接件单";
                        //        alogx.OperationType = (int)OperationType.Update;
                        //        LogDal.Instance.Insert(alogx);
                        //    //}
                            //else
                            //{
                            //    tranedit.Rollback();//事务回滚
                            //    context.Response.Write("{\"status\":0,\"msg\":\"该单已走上流程,不允许编辑接件单,请与管理员联系\" }");
                            //}

                        //}
                    }

                    catch (Exception e)
                    {
                        string kk = e.Message;
                        tranedit.Rollback();
                        context.Response.Write("{\"status\":0,\"msg\":\"系统错误,请与管理员联系\" }");
                    }
                    #endregion

                    break;

                case "editlcd"://修改流程单
                    #region 数据库事务
                    SqlTransaction traneditlcd = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {
                        //编辑流程单，有些字段不更新
                        JydOrderModel d = new JydOrderModel();
                        d.InjectFrom(rpm.Entity);
                        d.KeyId = rpm.KeyId;
                        //只更新以下主字段
                        //剔除不更新字段"KeyId","OrderYear", "OrderInt", "OrderID", 注意大写的也不更新
                        //string[] up = { "dept", "deptid" };
                        //string[] up = { "BBB", "AAA" };//修改流程单主订单什么都不修改
                        //DbUtils.tranUpdateOnlyUpdateFields(d, traneditlcd, up);
                        #region 更新明细表
                        JArray detailArr = JArray.Parse(detailJson);
                        for (int ii = 0; ii < detailArr.Count; ii++)//循环
                        {
                            var detailobj = JSONhelper.ConvertToObject<JydOrderDetailModel>(detailArr[ii]["d"].ToString());//根据模型把明细表转化为obj
                            JydOrderDetailModel detailModel = new JydOrderDetailModel();//初始化明细表模型
                            detailModel.InjectFrom(detailobj);//把obj插入模型

                            //只更新以下字段 
                            //剔除不更新的字段"KeyId", "orderid", "omainid",
                            //流程单要更新的字段
                            string[] upfiles = { "kzcc", "kzccb", "zs", "zsb", "fs", "fsb", "pss", "pssb", "pst", "pstb", "fbyq", "fbyqb", "jx", "jxb" };
                            //工艺要更新的字段
                            string[] gyfiles = { "fumoa", "fumoab", "fumob", "fumobb", "tana", "tanab", "tanb", "tanbb", "uva", "uvab", "uvb", "uvbb", "db", "dbb", "sh", "shb", "yaa", "yaab", "yab", "yabb", "zheye", "zheyeb", "zd", "zdb", "bh", "bhb", "sk", "skb", "dddd", "ddddb" };
                            string[] merge = upfiles.Concat(gyfiles).ToArray();//数组合并
                            DbUtils.tranUpdateOnlyUpdateFields(detailModel, traneditlcd, merge);
                        }
                        //生成二维码
                        string QRCodeUrl = QRCode.Generate(ConfigHelper.GetValue("website") + "/JydModleOrder/QRCodeView.aspx?KeyID=" + d.KeyId, @"JydModleOrder\img\jyd.png", DateTime.Now.ToString("yyyyMMdd"));
                        //每添加修改一条数据动态改变二维码
                        DbUtils.tranExecuteNonQuery("update JydOrder set order_img='" + QRCodeUrl + "' where KeyId=" + d.KeyId, traneditlcd);

                        #endregion

                        //从数据库里获得订单当前状态
                        orderStatus = (int)DbUtils.tranExecuteScalar("select mystatus from jydorder where keyid=" + d.KeyId + "", traneditlcd);

                        //为了思路清晰,订单状态单独更新
                        DbUtils.tranExecuteNonQuery("update jydorder set status=status+',1',mystatus=1 where keyid=" + d.KeyId + "", traneditlcd);

                        //判断是否是超管如果是超管可以任意修改
                        bool isadmin = SysVisitor.Instance.IsAdmin;
                        pageStatus = 1;
                        if (isadmin)//如果是超管
                        {
                            traneditlcd.Commit();//提交事务
                            //context.Response.Write("1");
                            context.Response.Write("{\"status\":1,\"msg\":\"修改成功\" }");

                            LogModel logxy = new LogModel();
                            logxy.BusinessName = SysVisitor.Instance.cookiesUserId + "超管修改了流程单1";
                            logxy.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                            logxy.OperationTime = DateTime.Now;
                            logxy.PrimaryKey = "";
                            logxy.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                            logxy.SqlText = "开单";
                            logxy.TableName = "jydOrder";
                            logxy.note = "超管修改了流程单";
                            logxy.OperationType = (int)OperationType.Update;
                            LogDal.Instance.Insert(logxy);
                        }
                        else//如果不是超管
                        {

                            if (orderStatus <= pageStatus)//订单状态小于等于页面状态
                            {
                                traneditlcd.Commit();//提交事务
                                //context.Response.Write("1");
                                context.Response.Write("{\"status\":1,\"msg\":\"修改成功\" }");

                                LogModel logxu = new LogModel();
                                logxu.BusinessName = SysVisitor.Instance.cookiesUserId + "管理员修改了流程单";
                                logxu.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                                logxu.OperationTime = DateTime.Now;
                                logxu.PrimaryKey = "";
                                logxu.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                                logxu.SqlText = "开单";
                                logxu.TableName = "jydOrder";
                                logxu.note = "管理员修改了流程单";
                                logxu.OperationType = (int)OperationType.Update;
                                LogDal.Instance.Insert(logxu);

                            }
                            else
                            {
                                traneditlcd.Rollback();//事务回滚
                                //context.Response.Write("0");
                                context.Response.Write("{\"status\":0,\"msg\":\"该单已收货签收,不允许修改流程单!\" }");
                            }

                        }

                    }

                    catch (Exception e)
                    {
                        traneditlcd.Rollback();
                        //context.Response.Write("0");
                        context.Response.Write("{\"status\":0,\"msg\":\"系统错误,请与管理员联系!\" }");
                    }
                    #endregion
                    break;
                case "export":
                    #region 导出 Excel
                    //string fields = rpm.fields;
                    string fields = rpm.CurrentContext.Request["fields"];
                    string tablename = TableConvention.Resolve(typeof(JydOrderModel));//得到表名
                    DataTable xlsDt = SqlEasy.ExecuteDataTable("select " + fields + " from " + tablename + "");
                    ExcelHelper.NPIOtoExcel(xlsDt, HttpContext.Current.Server.MapPath("\\upload\\excel\\" + tablename + ".xls"));
                    context.Response.Write("{\"status\":\"ok\",\"filename\":\"" + tablename + ".xls\"}");
                    #endregion
                    break;
                case "inport"://从Excel导入到数据库
                    #region 从Excel导入到数据库
                    if (context.Request["REQUEST_METHOD"] == "OPTIONS")
                    {
                        context.Response.End();
                    }
                    SaveFile("~/temp/", context);
                    #endregion
                    break;
                case "quandansk":
                    #region  全单收款
                    JydOrderModel q = new JydOrderModel();
                    q.InjectFrom(rpm.Entity);
                    q.KeyId = rpm.KeyId;
                    if (decimal.Parse(q.szp) > 0)
                    {
                        q.szpje = decimal.Parse(q.szp);
                        q.szp = DateTime.Now.ToString();
                    }
                    else
                    {
                        q.szpje = 0;
                        q.szp = null;
                    }

                    if (decimal.Parse(q.sxj) > 0)
                    {
                        q.sxjje = decimal.Parse(q.sxj);
                        q.sxj = DateTime.Now.ToString();
                    }
                    else
                    {
                        q.sxjje = 0;
                        q.sxj = null;
                    }
                    //全单收款只更新以下字段
                    string[] qfiles = { "kkyy", "kkkje", "zph", "szp", "szpje", "sxj", "sxjje", "skje", "zrrid", "zrr" };
                    DbUtils.UpdateOnlyUpdateFields(q, qfiles);
                    //全单收款 更新状态
                    SqlEasy.ExecuteNonQuery("update jydOrder set mystatus=3,status=status + ',3' where keyid=" + q.KeyId + "");
                    context.Response.Write("1");

                    LogModel logx = new LogModel();
                    logx.BusinessName = SysVisitor.Instance.cookiesUserId + "管理员选择全单收款1";
                    logx.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                    logx.OperationTime = DateTime.Now;
                    logx.PrimaryKey = "";
                    logx.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                    logx.SqlText = "全单收款";
                    logx.TableName = "jydOrder";
                    logx.note = "全单收款成功";
                    logx.OperationType = (int)OperationType.Update;
                    LogDal.Instance.Insert(logx);
                    #endregion
                    break;
                case "zddsk"://子订单收款
                    #region 子订单收款
                    JydOrderDetailModel jydd = new JydOrderDetailModel();
                    //把json转为模型
                    var rpmdd = new RequestParamModel<JydOrderDetailModel>(context) { CurrentContext = context };
                    if (!string.IsNullOrEmpty(json))
                    {
                        rpmdd = JSONhelper.ConvertToObject<RequestParamModel<JydOrderDetailModel>>(json);
                        rpmdd.CurrentContext = context;
                    }
                    jydd.InjectFrom(rpmdd.Entity);
                    jydd.KeyId = rpm.KeyId;
                    if (decimal.Parse(jydd.szp) > 0)
                    {
                        jydd.szpje = decimal.Parse(jydd.szp);
                        jydd.szp = DateTime.Now.ToString();
                    }
                    else
                    {
                        jydd.szpje = 0;
                        jydd.szp = null;
                        jydd.skje = jydd.szpje;//判断结清主要是判断收款金额
                    }

                    if (decimal.Parse(jydd.sxj) > 0)//假如收现金
                    {
                        jydd.sxjje = decimal.Parse(jydd.sxj);
                        jydd.sxj = DateTime.Now.ToString();
                        jydd.skje = jydd.sxjje;//判断结清主要是判断收款金额
                    }
                    else
                    {
                        jydd.sxjje = 0;
                        jydd.sxj = null;
                    }
                    //全单收款只更新以下字段
                    string[] ddqfiles = { "kkyy", "skje", "kkkje", "zph", "szp", "szpje", "sxj", "sxjje", "skje", "zrrid", "zrr" };
                    DbUtils.UpdateOnlyUpdateFields(jydd, ddqfiles);
                    //全单收款 更新状态
                    //SqlEasy.ExecuteNonQuery("update jydOrder set mystatus=3,status=status + ',3' where keyid=" + q.KeyId + "");
                    context.Response.Write("1");

                    LogModel logxo = new LogModel();
                    logxo.BusinessName = SysVisitor.Instance.cookiesUserId + "管理员选择全单收款";
                    logxo.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                    logxo.OperationTime = DateTime.Now;
                    logxo.PrimaryKey = "";
                    logxo.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                    logxo.SqlText = "全单收款";
                    logxo.TableName = "jydOrder";
                    logxo.note = "全单收款成功";
                    logxo.OperationType = (int)OperationType.Update;
                    LogDal.Instance.Insert(logxo);
                    #endregion
                    break;
                case "waisongjg"://外送加工


                    #region 外送加工
                    JydOrderDetailModel wsdd = new JydOrderDetailModel();
                    //把json转为模型
                    var rpmws = new RequestParamModel<JydOrderDetailModel>(context) { CurrentContext = context };
                    if (!string.IsNullOrEmpty(json))
                    {
                        rpmws = JSONhelper.ConvertToObject<RequestParamModel<JydOrderDetailModel>>(json);
                        rpmws.CurrentContext = context;


                    }
                    wsdd.InjectFrom(rpmws.Entity);
                    wsdd.KeyId = rpm.KeyId;
                    DataRow dataRow = SqlEasy.ExecuteDataRow("select * from jydorderdetail where keyid='" + wsdd.KeyId + "'");
                    string ai = rpm.KeyId + "_" + timeunix(DateTime.Now).ToString();
                    SqlTransaction eatran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    JydorderhoujiagongModel jydorderhoujiagong = new JydorderhoujiagongModel
                    {
                        orderid = dataRow["orderid"].ToString(),
                        myws = rpmws.Entity.myws,
                        myxd = rpmws.Entity.myxd,
                        adddate = rpmws.Entity.myxdrq,
                        mysh = rpmws.Entity.mysh,
                        myjhrq = rpmws.Entity.myjhrq,
                        yspmc = ai,
                        mycc = rpmws.Entity.mycc,
                        mynum = rpmws.Entity.mynum,
                        actual_quantity = rpmws.Entity.actual_quantity.ToString(),
                        receiving_time = rpmws.Entity.receiving_time,
                        mydj = rpmws.Entity.mydj,
                        myysf = decimal.Parse(rpmws.Entity.myysf),
                        myzzxm = rpmws.Entity.myzzxm,
                        wsjgbz = rpmws.Entity.wsjgbz,
                        status_fk = rpmws.Entity.status_fk,
                        orderkeyid = rpm.KeyId,
                        lccc = rpmws.Entity.lccc,
                        order_img = QRCode.Generate(ConfigHelper.GetValue("website") + "/JydModleOrder/outwarddelivery.aspx?yspmc=" + ai, @"JydModleOrder\img\jyd.png", DateTime.Now.ToString("yyyyMMdd"))
                    };
                    DbUtils.tranInsert(jydorderhoujiagong, eatran);//提交流程操作记录

                    //外送单只更新以下字段
                    string[] wsfiles = { "mywsid", "myws", "myxd", "myxdid", "myxdrq", "mysh", "myshid", "myjhrq", "mycc", "mynum", "mydj", "myysf", "myzzxm", "wsjgbz", "status_fk" };
                    DbUtils.UpdateOnlyUpdateFields(wsdd, wsfiles);
                    //生成二维码
                    string QRCodeUrlo = QRCode.Generate(ConfigHelper.GetValue("website") + "/JydModleOrder/outwarddelivery.aspx?yspmc=" + ai, @"JydModleOrder\img\jyd.png", DateTime.Now.ToString("yyyyMMdd"));
                    //每添加修改一条数据动态改变二维码
                    int lv = SqlEasy.ExecuteNonQuery("update jydOrderDetail set order_img='" + QRCodeUrlo + "' where KeyId=" + wsdd.KeyId + "");
                    eatran.Commit();//提交事务
                    //全单收款 更新状态
                    //SqlEasy.ExecuteNonQuery("update jydOrder set mystatus=3,status=status + ',3' where keyid=" + q.KeyId + "");
                    context.Response.Write("你来了，好久不见" + lv);
                    LogModel logxp = new LogModel();
                    logxp.BusinessName = SysVisitor.Instance.cookiesUserId + "选择外送加工";
                    logxp.OperationIp = context.Request.ServerVariables["REMOTE_ADDR"];
                    logxp.OperationTime = DateTime.Now;
                    logxp.PrimaryKey = "";
                    logxp.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                    logxp.SqlText = "全单收款";
                    logxp.TableName = "jydOrder";
                    logxp.note = "外送加工成功";




                    logxp.OperationType = (int)OperationType.Update;
                    LogDal.Instance.Insert(logxp);

                    //为模版中的各属性赋值
                    var templateData = new ProductTemplateData()
                    {
                        first = new TemplateDataItem(SysVisitor.Instance.cookiesUserName + "请您审核以下备料订单：JYD" + dataRow["orderid"].ToString(), "#000000"),
                        keyword1 = new TemplateDataItem(dataRow["orderid"].ToString(), "#000000"),
                        keyword2 = new TemplateDataItem(rpmws.Entity.myysf + "数量:" + rpmws.Entity.mynum, "#000000"),
                        keyword3 = new TemplateDataItem(DateTime.Now.ToString(), "#000000"),



                        keyword4 = new TemplateDataItem(rpmws.Entity.myws, "#000000"),
                        remark = new TemplateDataItem("备注:" + rpmws.Entity.wsjgbz + "，请尽快审核！", "#000000")
                    };
                    string templateid = NetWing.Common.ConfigHelper.GetValue("templageid2");//从web.config 获得模板ID
                                                                                            //通知所有员工就是openid不同
                    DataTable dta = SqlEasy.ExecuteDataTable("select * from Sys_Users where openid<>'' and IsAdmin = 1");
                    foreach (DataRow ndr in dta.Rows)
                    {
                        string openid = ndr["openid"].ToString();
                        string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(openid, templateid, NetWing.Common.ConfigHelper.GetValue("website") + "JydModleOrder/wsjgd_print.aspx", templateData);
                    }

                    #endregion
                    break;
                case "delete":
                    #region 删除
                    context.Response.Write(JydOrderBll.Instance.Delete(rpm.KeyId));
                    #endregion
                    break;
                case "alldel"://2017-04-05新增的功能 批量删除删除结果返回删除条数
                    #region 2017-04-05新增的功能 批量删除删除结果返回删除条数
                    context.Response.Write(NetWing.Dal.JydOrderDal.Instance.Delete(rpm.KeyIds));
                    #endregion
                    break;
                case "bl":
                    string orderid = context.Request["orderid"];
                    DataTable data = SqlEasy.ExecuteDataTable("Select * FROM (SELECT ROW_NUMBER()Over(order by o.KeyId desc) as rowId,o.orderid,od.yspmc,od.sl from jydOrder as o,jydOrderDetail as od where od.orderid=o.OrderID and o.OrderID='" + orderid + "') as mytable");
                    string oi = JSONhelper.ToJson(data);
                    context.Response.Write(JSONhelper.ToJson(data));
                    break;
                case "sousuo":
                    string sousu = context.Request["q"];
                    DataTable table = SqlEasy.ExecuteDataTable("select top 20 * from jydorder where orderid like '%" + sousu + "%'");
                    context.Response.Write(JSONhelper.ToJson(table));
                    break;
                default:
                    #region 显示
                    //string sqlwhere = "(deptid in (" + SysVisitor.Instance.cookiesUserDepId + "))";
                    //if (SysVisitor.Instance.cookiesIsAdmin == "True")
                    //{ 判断是否是超管如果是超管理，所有显示
                    string sqlwhere = " 1=1 ";//如果是超管则不显示
                    //}
                    if (!string.IsNullOrEmpty(rpm.Filter))//如果筛选不为空
                    {
                        string str = " and " + FilterTranslator.ToSql(rpm.Filter);
                        sqlwhere = sqlwhere + str;
                    }

                    string sort = rpm.Sort;
                    if (sort == null)
                    {
                        sort = "keyid desc";
                    }
                    //TableConvention.Resolve(typeof(MJUserModel)) 转换成表名
                    var pcpstr = new ProcCustomPage(TableConvention.Resolve(typeof(JydOrderModel)))
                    {
                        PageIndex = rpm.Pageindex,
                        PageSize = rpm.Pagesize,
                        //OrderFields = rpm.Sort,
                        OrderFields = sort,
                        WhereString = sqlwhere
                    };
                    int recordCount;
                    DataTable dt = DbUtils.GetPageWithSp(pcpstr, out recordCount);
                    dt.Columns.Add("khmcANDyspmc", typeof(string));//增加一列印刷品名称和客户名称
                    int i = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        //得到子订单Dt
                        string yspmc = "";
                        DataTable tempDt = SqlEasy.ExecuteDataTable("SELECT * FROM jydOrderDetail where orderid='" + dr["orderid"].ToString() + "'");
                        int j = 1;
                        foreach (DataRow tempDr in tempDt.Rows)
                        {
                            if (tempDr["printyes"].ToString() == "1")
                            {
                                yspmc = yspmc + j + "." + tempDr["yspmc"].ToString() + "√";
                            }
                            else
                            {
                                yspmc = yspmc + j + "." + tempDr["yspmc"].ToString();
                            }
                            j = j + 1;

                        }

                        dt.Rows[i]["khmcANDyspmc"] = dt.Rows[i]["comname"] + "&nbsp;&nbsp;&nbsp;" + yspmc;//修改dt的值
                        i = i + 1;
                    }



                    DataTable newdt = dt;

                    context.Response.Write(JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, newdt));
                    //context.Response.Write(JydOrderBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    #endregion
                    break;
            }
        }

        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;

            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);
            //清空temp文件夹
            DirFileHelper.ClearDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];

            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }

            var full = basePath + name;
            files[0].SaveAs(full);

            DataTable dt = NPOIHelper.ImportExceltoDt(full);
            string connectionString = SqlEasy.connString;
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = TableConvention.Resolve(typeof(JydOrderModel));
            //数据库中的表名
            //自定义的datatable和数据库的字段进行对应  
            //sqlBC.ColumnMappings.Add("id", "tel");  
            //sqlBC.ColumnMappings.Add("name", "neirong");  
            int k = dt.Rows.Count - 1;  //注意一个问题，最后一列是字段数
            for (int i = 0; i < (dt.Columns.Count - 1); i++)
            {
                sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());

            }
            var _result = "";
            try
            {
                sqlbulkcopy.WriteToServer(dt);
                _result = "{\"msg\" : \"导入数据库成功!\", \"result\" : " + k + ", \"filename\" : \"" + name + "\"}";
            }
            catch (Exception)
            {
                _result = "{\"msg\" : \"导入失败,可能模板不对，或其他原因，建议导出数据作为模板重新处理。注意导入没有校验数据重复功能。请人工校验数据!\", \"result\" : 0, \"filename\" : \"" + name + "\"}";
                //throw;
            }



            System.Web.HttpContext.Current.Response.Write(_result);

        }



        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}